package richbar.com.richbar.activity.product;

import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.common.base.BaseActivity;
import com.common.util.LogUtil;
import com.common.util.StringUtil;
import com.common.util.ToastUtil;
import com.okhttp.GlideUtil;
import com.okhttp.network.HttpUtils;
import com.okhttp.network.MyGson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import richbar.com.richbar.R;
import richbar.com.richbar.activity.me.ManageGoodsAddressAc;
import richbar.com.richbar.base.BaseApplication;
import richbar.com.richbar.bean.AddressResult;
import richbar.com.richbar.bean.Bean;
import richbar.com.richbar.bean.GoodsInfoResult;
import richbar.com.richbar.bean.OrderBean;
import richbar.com.richbar.bean.OrderSubResult;
import richbar.com.richbar.bean.SelectPayKindBean;
import richbar.com.richbar.bean.SetAddressResult;
import richbar.com.richbar.help.Constants;
import richbar.com.richbar.help.TitleHelp;
import richbar.com.richbar.util.LoadingDialog;
import richbar.com.richbar.util.NetWorkUtil;
import richbar.com.richbar.util.Util;
import richbar.com.richbar.view.pop.CommonBottomPop;
import richbar.com.richbar.view.pop.SelectAddressPop;

/**
 * Created by QiYang on 2018/11/21.
 */

public class FirmOrderAc extends BaseActivity {
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.tel)
    TextView tel;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.shop_name)
    TextView shopName;
    @BindView(R.id.pic)
    ImageView pic;
    @BindView(R.id.goods_name)
    TextView goodsName;
    @BindView(R.id.standard)
    TextView standard;
    @BindView(R.id.price_left)
    TextView priceLeft;
    @BindView(R.id.price_right)
    TextView priceRight;
    @BindView(R.id.num)
    TextView num;
    @BindView(R.id.pay_way)
    TextView payWay;
    @BindView(R.id.distribution_way)
    TextView distributionWay;
    @BindView(R.id.payment_way)
    TextView paymentWay;

    @BindView(R.id.invoice)
    TextView invoice;
    @BindView(R.id.message)
    EditText message;
    @BindView(R.id.goods_price)
    TextView goodsPrice;
    @BindView(R.id.freight)
    TextView freight;
    @BindView(R.id.beans)
    TextView beans;
    @BindView(R.id.voucher)
    TextView voucher;
    @BindView(R.id.gold)
    TextView gold;
    @BindView(R.id.pay_money_left)
    TextView payMoneyLeft;
    @BindView(R.id.pay_money_right)
    TextView payMoneyRight;

    private String goods_id;
    private String addressId = "";
    private String str_address = "";
    private String shipping = "1";
    private String pay_method = "1";
    private String str_invoice = "1";
    private String str_remark = "";
    private String amount = "";
    private String balance = "";
    private String score = "";
    private String coupon = "";
    private String invoice_name = "";
    private String invoice_type = "";
    private String goods = "";
    private String iv;

    private String selectValues;
    private int selectnum;
    private String selectPrice;
    private String selectId;
    GoodsInfoResult.DataEntity.InfoEntity bean;
    private LoadingDialog loadingDialog;
    public static String Orderid = "";
    public static boolean bln_kind = false;//false 购物车订单 true 个人中心充值

    @Override
    public int initLayout() {
        return R.layout.ac_firm_order;
    }

    @Override
    public void initTitle() {
        new TitleHelp(this).setTitle("确认订单");
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        loadingDialog = new LoadingDialog(this, 0);
    }

    @Override
    public void initData() {
        goods_id = getBundle().getString("id");
        selectValues = getBundle().getString("values");
        String num = getBundle().getString("num");
        selectnum = Integer.valueOf(num);
        selectId = getBundle().getString("ids");
        selectPrice = getBundle().getString("price");
        iv = getBundle().getString("pic");
        getData();
        LogUtil.e("PPPPPPPPPPPPP", "=" + selectValues + "--" + num);
        GlideUtil.loadImage(this,NetWorkUtil.URL + iv,pic);
    }

    private void getData() {
        NetWorkUtil.goodsInfo(goods_id, Util.md5(), new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String data) {
                final GoodsInfoResult result = MyGson.getInstance().fromJson(data, GoodsInfoResult.class);
                if (checkIsOk(result)) {
                    setData(result);
                }
            }
        });
    }

    private void setData(GoodsInfoResult result) {
        bean = result.getData().getInfo();
        name.setText(bean.getAddress_person());
        tel.setText(bean.getAddress_mobile());
        address.setText(bean.getAddress());
        goodsName.setText(bean.getGoods_name());
        standard.setText(selectValues);
        num.setText(selectnum + "");
        addressId = bean.getAddress_id();
        str_address=bean.getAddress();
        String price = bean.getGoods_price();
        goodsPrice.setText(price);
        if (!StringUtil.isEmpty(price)) {
            priceLeft.setText(price.substring(0, price.indexOf(".")));
            priceRight.setText(price.substring(price.indexOf("."), goodsPrice.length()));
            payMoneyLeft.setText(price.substring(0, price.indexOf(".")));
            payMoneyRight.setText(price.substring(price.indexOf("."), goodsPrice.length()));
        }


    }

    @OnClick({R.id.address_body, R.id.add, R.id.sub, R.id.pay_way_body, R.id.distribution_way_body, R.id.payment_way_body, R.id.invoice_body, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.address_body:
                if(!str_address.equals(""))
                showAddress();
                else
                start(ManageGoodsAddressAc.class);
                break;
            case R.id.add:
                selectnum++;
                num.setText(selectnum + "");
                break;
            case R.id.sub:
                if (selectnum > 1) {
                    selectnum--;
                    num.setText(selectnum + "");
                }
                break;
            case R.id.pay_way_body:
                showPay();
                break;
            case R.id.distribution_way_body:
                showDelivery();
                break;
            case R.id.payment_way_body:
                showPayment();
                break;
            case R.id.invoice_body:
                showInvoice();
                break;
            case R.id.submit:
                submit();
                break;
        }

    }

    private void showAddress() {
        SelectAddressPop pop = new SelectAddressPop(FirmOrderAc.this);
        pop.show(address, new SelectAddressPop.Callback() {
            @Override
            public void onAddressId(AddressResult.AddressBean bean) {
                LogUtil.e("PPPPPAPPA", bean.getId());
                addressId = bean.getId();
                address.setText(bean.getAddress());
                name.setText(bean.getName());
                tel.setText(bean.getMobile());
                NetWorkUtil.setAddress(bean.getId(), new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        loadingDialog.dismiss();
                        final SetAddressResult result = MyGson.getInstance().fromJson(data, SetAddressResult.class);
                    }
                });
            }

            @Override
            public void onSelectOtherAddress() {

            }
        });
    }

    private void submit() {
        String goods = goods_id + "@@" + selectnum + "@@" + selectPrice + "@@" + selectId;
        String msg = StringUtil.getStr(message);
        if (StringUtil.isEmpty(msg)) {
            msg = " ";
        }
        if (!str_address.equals("")) {
            NetWorkUtil.subitOrder(addressId, amount, msg, shipping, balance, pay_method, score, coupon,
                    str_invoice, invoice_name, invoice_type, goods, new HttpUtils.HttpCallback() {
                        @Override
                        public void onSuccess(String data) {
                            final OrderSubResult result = MyGson.getInstance().fromJson(data, OrderSubResult.class);
                            if (result.getCode().equals("200")) {
                                if (!StringUtil.isEmpty(result.getData().getOrderid())) {
//                                ToastUtil.showToast(FirmOrderAc.this,"提交成功");
                                    Orderid = result.getData().getOrderid();
                                    bln_kind = true;
                                    finish();
                                    sendPayRequest(result);
                                }

                            } else {
                                ToastUtil.showToast(FirmOrderAc.this, result.getMsg());
                            }

                        }
                    });
        } else
        {
            start(ManageGoodsAddressAc.class);
            ToastUtil.showToast(FirmOrderAc.this, "请选择收货地址");
        }


    }

    /**
     * 调用微信支付
     */
    public void sendPayRequest(OrderSubResult orderBean) {
        try {
            PayReq req = new PayReq();
            req.appId = Constants.APP_ID;
            req.partnerId = orderBean.getData().getPayOption().getPartnerid();
            req.prepayId = orderBean.getData().getPayOption().getPrepayid();
            req.nonceStr = orderBean.getData().getPayOption().getNoncestr();
            req.timeStamp = orderBean.getData().getPayOption().getTimestamp();
            req.packageValue = orderBean.getData().getPayOption().getPackageX();
            req.sign = orderBean.getData().getPayOption().getSign();
            req.extData = "app data"; // optional
            Toast.makeText(FirmOrderAc.this, "调起微信支付", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            BaseApplication.iwxapi.sendReq(req);

        } catch (Exception e) {
            Log.e("PAY_GET", "异常：" + e.getMessage());
            Toast.makeText(FirmOrderAc.this, "异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();

        }
    }

    private void showPay() {
        CommonBottomPop pop = new CommonBottomPop(this);
        List<Bean> data = new ArrayList<>();
        data.add(new Bean("1", "微信"));
        pop.show(payWay, "支付方式", data, new CommonBottomPop.Callback() {
            @Override
            public void callback(final Bean bean) {
                paymentWay.setText(bean.getValue());
            }
        });

    }

    private void showPayment() {
        CommonBottomPop pop = new CommonBottomPop(this);
        List<Bean> data = new ArrayList<>();
        data.add(new Bean("1", "全部现金"));
        data.add(new Bean("2", "全部金币"));
        data.add(new Bean("3", "待返金额"));
        data.add(new Bean("4", "已返金额"));
        data.add(new Bean("5", "蚂蚁豆支付"));
        data.add(new Bean("6", "蚂蚁券支付"));
        pop.show(paymentWay, "付款方式", data, new CommonBottomPop.Callback() {
            @Override
            public void callback(final Bean bean) {
                //dialog.show();
                NetWorkUtil.getSelectPayKind(bean.getId(), new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        //dialog.dismiss();
                        final SelectPayKindBean selectPayKindBean = MyGson.getInstance().fromJson(data, SelectPayKindBean.class);
                        if (selectPayKindBean.getCode() == 200) {
                            paymentWay.setText(bean.getValue());
                            pay_method = bean.getId();
                            beans.setText("");
                            voucher.setText("");
                            int iBeans = 0;
                            int iCoupon = 0;
                            if (bean.getId().equals("5")) {
                                iBeans = selectPayKindBean.getData().getCurrent();
                                score = selectPayKindBean.getData().getCurrent() + "";
                                beans.setText("-¥" + iBeans);
                            }
                            if (bean.getId().equals("6")) {
                                iCoupon = selectPayKindBean.getData().getCurrent();
                                coupon = selectPayKindBean.getData().getCurrent() + "";
                                voucher.setText("-¥" + iCoupon);
                            }
                            NetWorkUtil.getPrice(iBeans + "", iCoupon + "", "1", bean.getId(), selectId, new HttpUtils.HttpCallback() {
                                @Override
                                public void onSuccess(String data) {
                                    LogUtil.e("PDPDPPWPDPA", data);
                                }
                            });
                        }

                    }

                    @Override
                    public void onError(String msg) {
                        super.onError(msg);
                        //dialog.dismiss();
                    }
                });
            }
        });

    }


    private void showDelivery() {
        CommonBottomPop pop = new CommonBottomPop(this);
        List<Bean> data = new ArrayList<>();
        data.add(new Bean("1", "在线发货"));
        data.add(new Bean("2", "平台发货"));
        pop.show(distributionWay, "配送方式", data, new CommonBottomPop.Callback() {
            @Override
            public void callback(final Bean bean) {
                distributionWay.setText(bean.getValue());
                shipping = bean.getId();
            }
        });

    }

    private void showInvoice() {
        CommonBottomPop pop = new CommonBottomPop(this);
        List<Bean> data = new ArrayList<>();
        data.add(new Bean("2", "开具发票"));
        data.add(new Bean("1", "不开发票"));
        pop.show(invoice, "发票", data, new CommonBottomPop.Callback() {
            @Override
            public void callback(final Bean bean) {
                invoice.setText(bean.getValue());
                str_invoice = bean.getId();
            }
        });

    }
}
